import cv2
import numpy as np
import pyautogui

import pyperclip
from selenium import webdriver
import time
import base64
import requests
import json
import os
import cookie


def index():
    # 创建一个Chrome浏览器实例
    driver = webdriver.Chrome()
    # 打开谷歌浏览器，并访问指定的网址
    url = "https://www.baidu.com/s?wd=极速浏览器"
    # 访问url
    driver.get(url)
    # 放大
    x1, y1 = 890, 30
    pyautogui.moveTo(x1, y1, duration=0.5)
    pyautogui.click()
    time.sleep(1)
    # 检查
    x1, y1 = 110, 500
    pyautogui.moveTo(x1, y1, duration=0.5)
    pyautogui.rightClick()
    time.sleep(1)
    x1, y1 = 120, 900
    pyautogui.moveTo(x1, y1, duration=0.5)
    pyautogui.click()
    time.sleep(1)
    # 移动端
    x1, y1 = 1410, 222
    pyautogui.moveTo(x1, y1, duration=0.5)
    pyautogui.click()
    time.sleep(1)
    # 刷新页面
    x1, y1 = 95, 65
    pyautogui.moveTo(x1, y1, duration=0.5)
    pyautogui.click()
    time.sleep(1)

    # 给页面添加cookie
    cookies = cookie.getCookie()
    for key, value in cookies.items():
        driver.add_cookie({"name": key, "value": value})
    time.sleep(2)
    driver.get(url)
    # time.sleep(50)
    screenshot = pyautogui.screenshot()
    screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)  # 转换为BGR
    gray_screenshot = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)  # 转换为灰度图像
    return gray_screenshot


def screen_grab():
    """截取屏幕并返回灰度截图作为OpenCV图像"""
    screenshot = pyautogui.screenshot()
    screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)  # 转换为BGR
    gray_screenshot = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)  # 转换为灰度图像
    return gray_screenshot


def find_leftmost_match(screenshot, template):
    """在截图中查找模板图像，并返回最左侧匹配项的水平位置（如果没有找到，则返回None）"""
    res = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
    threshold = 0.8  # 可以根据需要调整阈值
    loc = np.where(res >= threshold)
    matches = list(zip(*loc[::-1]))
    return matches



    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

    # 注意：这里我们假设只关心最大匹配（即最相似的部分）
    # 如果需要找到所有匹配项，请遍历res矩阵并使用阈值

    if max_val < threshold:
        # 如果没有匹配项超过阈值，则返回None
        return None

        # max_loc是匹配项左上角的坐标
    return [min_loc, max_loc]
    # leftmost_x = max_loc[0]
    # return leftmost_x


def main():
    # 加载模板图像（确保路径正确）
    template_path = 'ab.png'
    template = cv2.imread(template_path, 0)  # 以灰度模式读取

    if template is None:
        print("Error: Unable to load template image.")
        return

        # 截取屏幕
    screenshot = index()
    # screenshot = screen_grab()

    # 查找最左侧的匹配项
    matches = find_leftmost_match(screenshot, template)

    for match in matches:
        x, y = match
        print(f"Match found at (x, y) = ({x}, {y})")

    # if most is not None:
    #     # print(f"Leftmost match found at x = {leftmost_x}")
    #     print(most)
    # else:
    #     print("No match found.")


if __name__ == "__main__":
    main()
